package com.jsu.clubmanagementsystem.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.user.AdminRegisterRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserAddRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserQueryRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserUpdateRequest;
import com.jsu.clubmanagementsystem.model.dto.userapplication.UserApplicationAddRequest;
import com.jsu.clubmanagementsystem.model.entity.User;
import com.jsu.clubmanagementsystem.model.entity.UserApplication;
import com.jsu.clubmanagementsystem.model.enums.ApplicationTypeEnum;
import com.jsu.clubmanagementsystem.model.vo.user.UserVO;
import com.jsu.clubmanagementsystem.service.application.UserApplicationService;
import com.jsu.clubmanagementsystem.service.club.ClubMembershipService;
import com.jsu.clubmanagementsystem.service.review.impl.AcceptedReviewProcessor;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class AdminUserController {

    @Resource
    private UserService userService;

    @Resource
    private ClubMembershipService clubMembershipService;

    @Resource
    private AcceptedReviewProcessor deleteUserProcessor;

    @Resource
    private UserApplicationService userApplicationService;

    /**
     * 管理员注册
     *
     * @param registerRequest
     * @return
     */
    @PostMapping("/admin/register")
    public BaseResponse<Boolean> adminRegister(@RequestBody AdminRegisterRequest registerRequest) {
        return ResultUtils.success(userService.adminRegister(registerRequest));
    }

    /**
     * 增加用户 (仅管理员)
     *
     * @param addRequest
     * @param request
     * @return
     */
    @PostMapping("/user/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员能使用此功能");
        }
        return ResultUtils.success(userService.addUser(addRequest));
    }

    /**
     * 删除用户 (仅管理员)
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/user/delete")
    public BaseResponse<Boolean> deleteUser(Long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员能使用此功能");
        }
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        User targetUser = userService.getById(id);
        if (targetUser == null){
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标用户不存在");
        }

        if (id.equals(loginUser.getId())) {
            userService.userLogout(request);
        }

        UserApplicationAddRequest deleteUserRequest = new UserApplicationAddRequest();
        deleteUserRequest.setUserId(id);
        deleteUserRequest.setReason("管理员操作删除用户");
        deleteUserRequest.setType(ApplicationTypeEnum.DELETE_USER.getCode());
        deleteUserRequest.setAdditionalInfo(id);
        Long applicationId = userApplicationService.processApplication(deleteUserRequest);

        if (!id.equals(loginUser.getId()) && !targetUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)) {
            UserApplication deleteUserApplication = userApplicationService.getById(applicationId);
            deleteUserProcessor.doDeleteUserApplicationReview(deleteUserApplication);
        }
        return ResultUtils.success(true);
    }

    /**
     * 修改用户信息 (仅管理员)
     *
     * @param updateRequest
     * @param request
     * @return
     */
    @PostMapping("/user/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest updateRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员能使用此功能");
        }
        if (updateRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        userService.updateUser(updateRequest);

        // 如果管理员更新的是自己的信息
        Long id = updateRequest.getId();
        if (id != null && id.equals(loginUser.getId())) {
            userService.updateLoginUser(id, request);
        }
        return ResultUtils.success(true);
    }

    /**
     * 查找用户 (仅管理员)
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<User> getUserById(long userId, HttpServletRequest request) {
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员能使用此功能");
        }
        User user = userService.getById(userId);
        if (user == null) {
            ResultUtils.error(ErrorCode.NOT_FOUND, "目标用户不存在");
        }
        return ResultUtils.success(user);
    }

    /**
     * 获取用户的封装对象
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/user/get/vo")
    public BaseResponse<UserVO> getUserVoById(Long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser.getUserRole().equals(UserConstant.USER_ROLE_USER)){
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限使用此功能");
        }
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        User user = userService.getById(id);
        return ResultUtils.success(UserVO.objToVoAllInfo(user));
    }

    /**
     * 查找用户 (仅管理员、分页)
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list")
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员能使用此功能");
        }
        // 获取QueryWrapper
        QueryWrapper<User> queryWrapper = userService.getQueryWrapper(queryRequest);
        // 处理Page
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        Page<User> page = userService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(page);
    }
}
